package com.giantlizard.cloud.common.security.utils;

import com.giantlizard.cloud.common.security.model.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;

/**
 * 安全服务工具类
 */
public class SecurityUtils {
    
    private static final AntPathMatcher antPathMatcher = new AntPathMatcher();
    
    /**
     * 获取用户ID
     */
    public static String getUserId() {
        try {
            return getLoginUser().getUserId();
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 获取用户名
     */
    public static String getUsername() {
        try {
            return getLoginUser().getUsername();
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 获取用户
     */
    public static LoginUser getLoginUser() {
        try {
            return (LoginUser) getAuthentication().getPrincipal();
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
    
    /**
     * 是否为管理员
     * @param userId 用户ID
     * @return 结果
     */
    public static boolean isAdmin(String userId) {
        return "1".equals(userId);
    }
    
    /**
     * 验证用户是否具有访问权限
     *
     * @param loginUser 登录用户
     * @param path 访问路径
     * @return 是否有权限
     */
    public static boolean hasPermission(LoginUser loginUser, String path) {
        // 验证用户权限
        return loginUser.getPermissions().stream()
                .anyMatch(permission -> antPathMatcher.match(permission, path));
    }
} 